//
//  ImageEngine.m
//  TestARC
//
//  Created by Rayco on 12-10-17.
//  Copyright (c) 2012年 Test. All rights reserved.
//

#import "AppsImageEngine.h"
#import <QuartzCore/CoreImage.h>

static AppsImageEngine *engine;
@implementation AppsImageEngine

@synthesize delegate;

+ (id)sharedEngine {
    if(!engine){
        engine = [[self alloc] init];
    }
    return engine;
}

- (void)loadImage:(NSString *)imageUrl onCompletion:(ImageEngineBlock)onCompletion {
    
    [self imageAtURL:[NSURL URLWithString:imageUrl] onCompletion:^(NSImage *fetchedImage, NSURL *url, BOOL isInCache) {
        onCompletion(fetchedImage,url,isInCache);
    }];
}

- (void)loadImage:(NSString *)imageUrl dimension:(CGSize)size onCompletion:(ImageEngineBlock)onCompletion {

    if(!imageUrl || [imageUrl isEqualToString:@""])
        return;
    NSString *ext = [imageUrl pathExtension];
    if(!ext || [ext isEqualToString:@""])
        return;

    NSString *pathWithOutExt = [imageUrl stringByDeletingPathExtension];
    NSString *newUrl = [pathWithOutExt stringByAppendingFormat:@"_r%ldx%ld",(NSInteger)size.width,(NSInteger)size.height];
    newUrl = [newUrl stringByAppendingPathExtension:ext];
    
    [self imageAtURL:[NSURL URLWithString:newUrl] onCompletion:^(NSImage *fetchedImage, NSURL *url, BOOL isInCache) {
        onCompletion(fetchedImage,url,isInCache);
    } ];
}

- (NSImage*) imageFromCGImageRef:(CGImageRef)image
{
    NSRect imageRect = NSMakeRect(0.0, 0.0, 0.0, 0.0);
    CGContextRef imageContext = nil;
    NSImage* newImage = nil;
    // Get the image dimensions.
    imageRect.size.height = CGImageGetHeight(image);
    imageRect.size.width = CGImageGetWidth(image);
    // Create a new image to receive the Quartz image data.
    newImage = [[NSImage alloc] initWithSize:imageRect.size];
    [newImage lockFocus];
    // Get the Quartz context and draw.
    imageContext = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
    CGContextDrawImage(imageContext, *(CGRect*)&imageRect, image);
    [newImage unlockFocus];
    return newImage;
}

- (BOOL)saveImage:(NSImage*)image                      //source image
         saveType:(NSBitmapImageFileType)storageType   //save type "NSJPEGFileType",NSPNGFileType
       properties:(NSDictionary *)properties         //properties "NSImageCompressionFactor = (NSNumber)0.8"
         ToTarget:(NSString *) targePath               //save path
{
    NSData *tempdata;
    NSBitmapImageRep *srcImageRep;
    BOOL reflag = NO;
    [image lockFocus];
    srcImageRep = [NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]];
    tempdata = [srcImageRep representationUsingType:storageType properties:properties];
    reflag = [tempdata writeToFile:targePath atomically:YES];
    [image unlockFocus];
    return reflag;
}

- (CGImageRef)nsImageToCGImageRef:(NSImage*)image;
{
    NSData * imageData = [image TIFFRepresentation];
    CGImageRef imageRef;
    if(imageData)
    {
        CGImageSourceRef imageSource =
        CGImageSourceCreateWithData((__bridge CFDataRef)imageData,  NULL);
        imageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
    }
    else {
        return nil;
    }
    
    return imageRef;
}


- (void)makeAppIconWithImageUrl:(NSString*)url saveAtPath:(NSString*)path {
    if (!url || url.length <= 0) {
        return;
    }
    icon57x57Done = NO;
    icon114x114Done = NO;
    icon512x512Done = NO;
    
    NSString *str_57x57 = [url stringByAppendingString:@"_r57x57.png"];
    NSString *str_114x114 = [url stringByAppendingString:@"_r114x114.png"];
    NSString *str_512x512 = [url stringByAppendingString:@"_r512x512.png"];
    [self loadImage:str_57x57 onCompletion:^(NSImage *fetchImage, NSURL *url, BOOL isInCache) {
        [self saveImage:fetchImage saveType:NSPNGFileType properties:nil ToTarget:[path stringByAppendingPathComponent:@"icon.png"]];
        icon57x57Done = YES;
        [self loadImageComplete:fetchImage];
    }];
    [self loadImage:str_114x114 onCompletion:^(NSImage *fetchImage, NSURL *url, BOOL isInCache) {
        [self saveImage:fetchImage saveType:NSPNGFileType properties:nil ToTarget:[path stringByAppendingPathComponent:@"icon@2x.png"]];
        icon114x114Done = YES;
        [self loadImageComplete:fetchImage];
    }];
    [self loadImage:str_512x512 onCompletion:^(NSImage *fetchImage, NSURL *url, BOOL isInCache) {
        [self saveImage:fetchImage saveType:NSPNGFileType properties:nil ToTarget:[path stringByAppendingPathComponent:@"iTunesArtwork"]];
        icon512x512Done = YES;
        [self loadImageComplete:fetchImage];
    }];
}

- (void)loadImageComplete:(NSImage*)_image {
    if (!icon114x114Done || !icon512x512Done || !icon57x57Done) {
        return;
    }
    if ([delegate respondsToSelector:@selector(AppsImageEngineLoadImageComplete:)]) {
        [delegate AppsImageEngineLoadImageComplete:_image];
    }
}

- (bool)isMakeingIconDone {
    if (icon512x512Done && icon114x114Done && icon57x57Done) {
        return YES;
    }
    return NO;
}

- (bool)isAndroidIconLoadingDone {
    if (androidIconDone >= 4) {
        [delegate AppsImageEngineLoadAndroidIconsComplete];
        return YES;
    }
    return NO;
}

- (void)loadAndroidIconWithImageUrl:(NSString*)url projectPath:(NSString*)pPath {
    //hdpi 72*72;ldpi 32*32;mdpi 48*48;xhdpi 96*96; icon.png
    androidIconDone = 0;
    NSString *ext = [url pathExtension];
    url = [url stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@".%@",ext] withString:@""];//去掉尾部
     NSString *iconH = [NSString stringWithFormat:@"%@_r72x72.%@",url,ext];
     NSString *iconL = [NSString stringWithFormat:@"%@_r32x32.%@",url,ext];
     NSString *iconM = [NSString stringWithFormat:@"%@_r48x48.%@",url,ext];
     NSString *iconXH = [NSString stringWithFormat:@"%@_r96x96.%@",url,ext];
    

    [self loadImage:iconH onCompletion:^(NSImage *fetchImage, NSURL *url, BOOL isInCache) {
        [self saveImage:fetchImage saveType:NSPNGFileType properties:nil ToTarget:[pPath stringByAppendingPathComponent:@"res/drawable-hdpi/icon.png"]];
        androidIconDone++;
        NSLog(@"icon for hdpi complete! No.%d\n",androidIconDone);
        [self isAndroidIconLoadingDone];
    }];
    [self loadImage:iconL onCompletion:^(NSImage *fetchImage, NSURL *url, BOOL isInCache) {
        [self saveImage:fetchImage saveType:NSPNGFileType properties:nil ToTarget:[pPath stringByAppendingPathComponent:@"res/drawable-ldpi/icon.png"]];
        androidIconDone++;
        NSLog(@"icon for ldpi complete! No.%d\n",androidIconDone);
        [self isAndroidIconLoadingDone];
    }];
    [self loadImage:iconM onCompletion:^(NSImage *fetchImage, NSURL *url, BOOL isInCache) {
        [self saveImage:fetchImage saveType:NSPNGFileType properties:nil ToTarget:[pPath stringByAppendingPathComponent:@"res/drawable-mdpi/icon.png"]];
        androidIconDone++;
        NSLog(@"icon for mdpi complete! No.%d\n",androidIconDone);
        [self isAndroidIconLoadingDone];
    }];
    [self loadImage:iconXH onCompletion:^(NSImage *fetchImage, NSURL *url, BOOL isInCache) {
        [self saveImage:fetchImage saveType:NSPNGFileType properties:nil ToTarget:[pPath stringByAppendingPathComponent:@"res/drawable-xhdpi/icon.png"]];
        [self saveImage:fetchImage saveType:NSPNGFileType properties:nil ToTarget:[pPath stringByAppendingPathComponent:@"res/drawable/icon.png"]];
        androidIconDone++;
        NSLog(@"icon for xhdpi complete! No.%d\n",androidIconDone);
        [self isAndroidIconLoadingDone];
    }];
}

- (void)loadAndroidIconsUsingGCDWithImageUrl:(NSString*)url projectPath:(NSString*)pPath {
    androidIconDone = 0;
    NSString *ext = [url pathExtension];
    url = [url stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@".%@",ext] withString:@""];//去掉尾部
    __block NSString *iconH = [NSString stringWithFormat:@"%@_r72x72.%@",url,ext];
    __block NSString *iconL = [NSString stringWithFormat:@"%@_r32x32.%@",url,ext];
    __block NSString *iconM = [NSString stringWithFormat:@"%@_r48x48.%@",url,ext];
    __block NSString *iconXH = [NSString stringWithFormat:@"%@_r96x96.%@",url,ext];
    
    dispatch_queue_t queue1 = dispatch_queue_create("DownloadIcons", NULL);
    dispatch_async(queue1, ^{
        NSImage *result;
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:iconH]];
        result = [[NSImage alloc] initWithData:data];
        [self saveImage:result saveType:NSPNGFileType properties:nil ToTarget:[pPath stringByAppendingPathComponent:@"res/drawable-hdpi/icon.png"]];
        androidIconDone++;
        NSLog(@"icon for hdpi complete! No.%d\n",androidIconDone);
        [self isAndroidIconLoadingDone];
    });
    
    dispatch_async(queue1, ^{
        NSImage *result;
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:iconL]];
        result = [[NSImage alloc] initWithData:data];
        
        [self saveImage:result saveType:NSPNGFileType properties:nil ToTarget:[pPath stringByAppendingPathComponent:@"res/drawable-ldpi/icon.png"]];
        androidIconDone++;
        NSLog(@"icon for ldpi complete! No.%d\n",androidIconDone);
        [self isAndroidIconLoadingDone];
    });
    
    dispatch_async(queue1, ^{
        NSImage *result;
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:iconM]];
        result = [[NSImage alloc] initWithData:data];
        
        [self saveImage:result saveType:NSPNGFileType properties:nil ToTarget:[pPath stringByAppendingPathComponent:@"res/drawable-mdpi/icon.png"]];
        androidIconDone++;
        NSLog(@"icon for mdpi complete! No.%d\n",androidIconDone);
        [self isAndroidIconLoadingDone];
    });
    
    dispatch_async(queue1, ^{
        NSImage *result;
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:iconXH]];
        result = [[NSImage alloc] initWithData:data];
        
        [self saveImage:result saveType:NSPNGFileType properties:nil ToTarget:[pPath stringByAppendingPathComponent:@"res/drawable-xhdpi/icon.png"]];
        [self saveImage:result saveType:NSPNGFileType properties:nil ToTarget:[pPath stringByAppendingPathComponent:@"res/drawable/icon.png"]];
        androidIconDone++;
        NSLog(@"icon for xhdpi complete! No.%d\n",androidIconDone);
        [self isAndroidIconLoadingDone];
    });
}

@end
